package cn.itcast.health.provider.service.impl;

import cn.itcast.health.commons.entity.QueryPageBean;
import cn.itcast.health.commons.entity.Result;
import cn.itcast.health.commons.resources.MessageConstant;
import cn.itcast.health.commons.resources.RedisConstant;
;
import cn.itcast.health.commons.utils.DateUtils;
import cn.itcast.health.interfaces.service.SetmealService;
import cn.itcast.health.mapper.CheckGroupMapper;
import cn.itcast.health.mapper.SetmealMapper;
import cn.itcast.health.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Autowired
    private JedisPool jedisPool;

    //依赖注入redisTemplate
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Result addSetmealAndSetmealCheckgroup(CheckSG checkSG) {
        Result result = null;
        try{
            Setmeal setmeal = checkSG.getSetmeal();
            Integer[] checkGroupIds = checkSG.getCheckGroupIds();
            setmealMapper.addSetmeal(setmeal);
            Integer setmealId = setmeal.getId();
            if(setmealId != null){
                setmealMapper.addSetmealCheckgroup(setmealId,checkGroupIds);
            }else {
                Integer id = setmealMapper.findByCodeSetmeal(setmeal.getCode());
                setmealMapper.addSetmealCheckgroup(id,checkGroupIds);
            }
            //  图片存储 redis
            Jedis jedis = jedisPool.getResource();
            jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
            jedis.close();
            result = new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e){
            result = new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return result;
    }

    @Override
    public Result findByPageSetmealData(QueryPageBean queryPageBean) {
        Result result = null;
        try {
            //设置分页条件
            PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
            //查询数据
            List<Setmeal> checkItems = setmealMapper.findByPageSetmealData(queryPageBean.getQueryString());

            PageInfo pageInfo = new PageInfo(checkItems);
            Map<String,Object> map = new HashMap();
            map.put("list",pageInfo.getList());
            map.put("total",pageInfo.getTotal());
            result = new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,map);
        }catch (Exception e){
            result = new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
        return result;
    }


    /**
     * 用于移动端的
     * @return
     */
    @Override
    public Result findAllSetmealData() {
        Result result = null;
        final String MARK = "SAVED_SETMEAL";
        List<Setmeal> setmeals = (List<Setmeal>) redisTemplate.opsForList().range(MARK, 0, -1);
        if (setmeals.size() != 0){
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeals);
        }
        try {
            setmeals = setmealMapper.findAllSetmealData();
            result = new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeals);
            redisTemplate.opsForList().rightPushAll(MARK,setmeals);
        }catch (Exception e){
            result = new Result(false,MessageConstant.QUERY_SETMEAL_FAIL );
        }
        return result;
    }


    /**
     * 更新套餐详情从redis中获取
     */
    @Override
    public Result findSetMealDetail(Integer id) {
        Result result = null;
        //定义存储标记
        final String MARK = "_SAVED_SETMEAL_DETAIL";
        Setmeal setmeals = (Setmeal) redisTemplate.opsForValue().get(id+MARK);

        //判断查询结果,如果存在直接返回,减轻服务器压力
        if (setmeals !=null){
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeals);
        }
        try {
            setmeals = setmealMapper.findSetMealDetail(id);
            List<CheckGroup> checkGroups = setmeals.getCheckGroups();
            for (CheckGroup checkGroup : checkGroups) {

                List<CheckItem>  checkItemList =  setmealMapper.findCheckItemsByCheckGroupId(checkGroup.getId());

                checkGroup.setCheckItems(checkItemList);//  封装每一个检查组 对应检查项信息
            }
            //在redis中没有查询到,存到redis中一份,以便下次查询
            redisTemplate.opsForValue().set(id+MARK,setmeals);

            result = new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeals);
        }catch (Exception e){
            result = new Result(false,MessageConstant.QUERY_SETMEAL_FAIL );
        }
        return result;
    }

    @Override
    public Result findByIdSetmealData(Integer id) {
        Result result = null;
        try {
            Setmeal setmeal = setmealMapper.findByIdSetmealData(id);
            result = new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        }catch (Exception e){
            result = new Result(false,MessageConstant.QUERY_SETMEAL_FAIL );
        }
        return result;
    }


    @Override
    public Result findByIdCheckitemAnaIdsData(Setmeal setmeal) {
        Result result = null;
        try {
            HashMap<String, Object> map = new HashMap<>();
            //调用检查项的mapper 中的查询所有的检查项
            List<CheckGroup> checkgroupAll = checkGroupMapper.findCheckgroupAll();
            Integer[] checkgroupIds = checkGroupMapper.findByIdCheckGroupAnaIdsData(setmeal.getId());
            map.put("list",checkgroupAll);
            map.put("checkgroups",checkgroupIds);
            result = new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,map);
        }catch (Exception e){
            result = new Result(true,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
        return result;
    }

    @Override
    public Result updateSetmealAndSetmealCheckGroupData(SetmealG setmealG) {
        Result result = null;
        try{
            Setmeal setmeal = setmealG.getSetmeal();
            Integer[] checkgroups = setmealG.getCheckgroups();
            String img = setmeal.getImg();
            //更新检查组的数据
            setmealMapper.updateSetmeal(setmeal);
            //删除关联表的数据 根据检查组的id
            setmealMapper.deleteByidSetmealCheckGroup(setmeal.getId());
            //添加中间表数据
            setmealMapper.addSetmealCheckgroup(setmeal.getId(),checkgroups);
            //添加成功后删除
            if(img != null  && img != ""){
                //  图片存储 redis
                Jedis jedis = jedisPool.getResource();
                jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
                jedis.close();
            }
            //修改信息完成后及时删除缓存
            String id = String.valueOf(setmeal.getId());

            //清除redis套餐列表信息
            while (redisTemplate.opsForList().size("SAVED_SETMEAL") > 0){
                redisTemplate.opsForList().leftPop("SAVED_SETMEAL");
            }
            //清除redis套餐详情信息
            redisTemplate.delete(id+"_SAVED_SETMEAL_DETAIL");
            result = new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
        }catch (Exception e){
            result = new Result(false,MessageConstant.EDIT_SETMEAL_FAIL);
        }
        return result;
    }

    @Override
    public Result deleteByIdSetmealData(Integer id) {
        Result result = null;
        try{
            setmealMapper.deleteByidSetmealCheckGroup(id);
            setmealMapper.deleteSetmeal(id);;
            //删除成功及时清除缓存
            redisTemplate.delete(String.valueOf(id)+"_SAVED_SETMEAL_DETAIL");
            result = new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result(false,MessageConstant.DELETE_SETMEAL_FAIL);
        }
        return result;
    }

    @Override
    public Result findByData(Integer id, String orderDate) {
        Result result = null;
        try{

            Date date = DateUtils.parseString2Date(orderDate, "yyyy-MM-dd");
            String date2String = DateUtils.parseDate2String(date, "yyyy-MM-dd");
            Map map = setmealMapper.findByData(id,date2String);
            result = new Result(true,MessageConstant.QUERY_ORDERSETTING_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result(false,MessageConstant.QUERY_ORDERSETTING_FAIL);
        }
        return result;
    }

    @Override
    public Result yuyuedata(Integer id) {
        Result result = null;
        try{
            List<Map> maps = setmealMapper.yuyuedata(id);
            result = new Result(true,MessageConstant.QUERY_ORDERSETTING_SUCCESS,maps);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result(false,MessageConstant.QUERY_ORDERSETTING_FAIL);
        }
        return result;
    }
}
